#include "PointerCheck.h"
#include "WinExHandler.h"

namespace helix
{

	bool PtrCheck::isValid(HObject *obj)
	{
		Win32ExceptionHandler::installHandler();
		int i=-20;
		bool valid = true;
		try
		{
			i=obj->GetRefCount();
			if(i==0xfeeefeee || i<-1)
				throw -1;
		}
		catch(int a)
		{
			if(a==-1)
				valid = false;
		}

		Win32ExceptionHandler::uninstallHandler();
		return valid;
	}

	bool PtrCheck::safeDelete(HObject *obj,const char* objName)
	{
		Win32ExceptionHandler::installHandler();
		bool valid = true;
		try
		{
			delete obj;
		}
		catch(AccessViolationException)
		{
			printf("\n%s: This object was already deleted.",objName);
			valid = false;
		}

		Win32ExceptionHandler::uninstallHandler();
		return valid;
	}

	//Only prints the message if the object should have been deleted.
	bool PtrCheck::safeDelete(HObject *obj,const char* objName,bool needsDeletion)
	{
		Win32ExceptionHandler::installHandler();
		bool valid = true;
		try
		{
			delete obj;
			if(!needsDeletion)
			{
				printf("\n%s: This object should have been deleted before now!");
				valid = false;
			}
		}
		catch(AccessViolationException)
		{
			if(needsDeletion)
			{
				printf("\n%s: This object was already deleted!",objName);
				valid = false;
			}
		}

		Win32ExceptionHandler::uninstallHandler();
		return valid;
	}

}